package com.ckr.util;

import com.ckr.config.PhotosConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

/**
 * @author Shadowckr
 * @create 2022-02-12 10:59
 * 调好的别乱动！
 * 生成 uuid 用户为图片，按照年月日创建文件夹，将文件放置于此
 * 返回 static下图片的相对存放位置：/BlogImg/2022/02/13/acfea1a1-fca6-4c5e-8e05-81e654de39751644721543492ycqs.jpg
 * 参数：@param: LoadPath:static目录下存放图片的根目录
 */

@Component
public class UpPhotoNameUtils {
    @Autowired
    PhotosConfig photosConfig;
    static String UserPicRoot = "static/";

    public String SaveUserPic(String LoadPath, MultipartFile file) {
        String contentType = file.getContentType();
        // 限制文件格式
        if (!photosConfig.getAllowTypes().contains(contentType)) {
            return null;
        }

        String filename = UUID.randomUUID().toString() + System.currentTimeMillis();
        // 先创建文件夹
        Calendar cad = Calendar.getInstance();
        String month = String.valueOf(cad.get(Calendar.MONTH) + 1);
        if (month.length() < 2) {
            month = "0" + month;
        }
        String day = String.valueOf(cad.get(Calendar.DAY_OF_MONTH));
        String SaveUserPicRoot = null;
        try {
            SaveUserPicRoot = ResourceUtils.getURL("classpath:").getPath() + UserPicRoot;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String RevPath = LoadPath + "/" + String.valueOf(cad.get(Calendar.YEAR)) + "/" + month + "/" + day;
        String savePath = SaveUserPicRoot + RevPath;
//        System.out.println(savePath);
//        /E:/workspace/java_project_myself/idea-project1/vueblog/target/classes/static/BlogImg/2022/02/13
        String realSavePath = savePath.replace('/', '\\').substring(1, savePath.length());
//        System.out.println(realSavePath);
        // 这个是为了拿到真实的存储地址
        // 返回结果如下：E:\workspace\java_project_myself\idea-project1\vueblog\target\classes\static\BlogImg\2022\02\13
        File dirFile = new File(realSavePath);
        boolean bFile = dirFile.exists();
        if (!bFile) {
            //noinspection ResultOfMethodCallIgnored
            dirFile.mkdirs();
        }

        RevPath = RevPath + "/" + filename + file.getOriginalFilename();
        savePath = (SaveUserPicRoot + RevPath);

        try {
            file.transferTo(new File(savePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

//        System.out.println(savePath);
        // /E:/workspace/java_project_myself/idea-project1/vueblog/target/classes/static/BlogImg/2022/02/13/acfea1a1-fca6-4c5e-8e05-81e654de39751644721543492ycqs.jpg
        return "/" + RevPath;
    }
}
